package com.lgy.controller;

import com.lgy.exception.SellException;
import com.lgy.utils.ServletUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @ClassName 全局异常处理
 * @Author liguangyao
 * @Date 3/11/2018 9:33 PM
 * @Version 1.0
 **/
@ControllerAdvice
public class ExceptionController extends BaseController {

    /**
     * 自定义异常处理
     * @param exception
     * @return 错误信息
     */
    @ExceptionHandler({SellException.class})
    public ModelAndView platformException(SellException exception) {
        if (ServletUtils.isAjaxRequest(getHttpServletRequest())) {
            returnMsg(HttpStatus.INTERNAL_SERVER_ERROR.value(), exception.getMessage());
            return null;
        } else {
            return new ModelAndView(ERROR_PAGE, "msg", exception.getMessage());
        }
    }

    /**
     * 参数校验
     *  @Valid 可以用在类型、方法和方法参数上。但是不能用在成员属性（字段）上
     *  @Validated 可以用在方法、构造函数、方法参数和成员属性（字段）上
     * @param exception
     * @return 错误信息
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ModelAndView authorizationException(MethodArgumentNotValidException exception) {
        BindingResult result = exception.getBindingResult();
        StringBuffer stringBuffer = new StringBuffer();
        if (ServletUtils.isAjaxRequest(getHttpServletRequest())) {
            if (result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                for (ObjectError error : errors) {
                    FieldError fieldError = (FieldError) error;
                    stringBuffer.append(fieldError.getField() + ":" + fieldError.getDefaultMessage() + " ");
                }
                returnMsg(HttpStatus.BAD_REQUEST.value(), stringBuffer.toString());
            }
            return null;
        } else {
            return new ModelAndView(ERROR_PAGE, "msg", stringBuffer);
        }
    }

    /**
     * 参数类型转换错误
     * @param exception
     * @return 错误信息
     */
    @ExceptionHandler({HttpMessageConversionException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ModelAndView parameterTypeException(HttpMessageConversionException exception){
        if (ServletUtils.isAjaxRequest(getHttpServletRequest())) {
            returnMsg(HttpStatus.INTERNAL_SERVER_ERROR.value(), "类型转换错误: " + exception.getCause().getLocalizedMessage());
            return null;
        } else {
            return new ModelAndView(ERROR_PAGE, "msg", exception.getMessage());
        }
    }

    /**
     * 系统异常处理
     * @param exception
     * @return
     */
    @ExceptionHandler({Exception.class})
    public ModelAndView exception(Exception exception) {
        if (ServletUtils.isAjaxRequest(getHttpServletRequest())) {
            returnMsg(HttpStatus.INTERNAL_SERVER_ERROR.value(), exception.getMessage());
            return null;
        } else {
            return new ModelAndView(ERROR_PAGE, "msg", exception.getMessage());
        }
    }
}
